'use strict';
const {
	appId,
	appSecret,
	getToken,
	verifyToken
} = require("wx-common");
const db = uniCloud.database();

exports.main = async (event, context) => {
	//获取前端参数
	const {
		code,
		nickName,
		gender,
		city,
		province,
		country,
		avatarUrl
	} = event;
	//获取openid
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`, {
			dataType: "json"
		}
	)
	let openid = res.data.openid;

	//获取user表
	const collection = db.collection('user');

	// 根据openid查询user表是否已有该用户
	const userInfo = await collection.where({
		openid
	}).get()

	// 获取当前时间
	const now = new Date().getTime();

	// 生成token
	let token = getToken(openid)

	if (userInfo.affectedDocs < 1 && nickName !== undefined && nickName !== undefined) {
		// 没有该用户 注册并返回用户信息
		let userData = {
			nickName,
			gender,
			city,
			province,
			country,
			avatarUrl,
			openid,
			createtime: now,
		}

		// 往user表添加用户信息
		const resData = await db.collection("user").add(userData)
		if (resData.id) {
			let data = {
				nickName,
				gender,
				city,
				province,
				country,
				avatarUrl,
				createtime: now,
			}
			return {
				code: 200,
				msg: '登录成功',
				data: {
					userInfo: data,
					token: token
				}
			}
		} else {
			// 添加失败
			return {
				code: 201,
				msg: '登录失败',
				data: resData
			}
		}
	} else if (userInfo.affectedDocs >= 1) {
		// 用户已注册直接返回用户信息
		let data = userInfo.data[0];
		if (data.createtime) {
			await db.collection("user").where({
				openid
			}).update({
				updatetime: now
			})
		} else {
			await db.collection("user").where({
				openid
			}).update({
				createtime: now,
				updatetime: now
			})
			data.createtime = now
		}
		data.updatetime = now
		delete data.openid;
		return {
			code: 200,
			msg: '获取成功',
			data: {
				userInfo: data,
				token: token
			}
		}
	} else {
		return {
			code: 200,
			msg: '获取成功',
			data: {}
		}
	}
};
